package cn.dqy.gotanserver.support.msghandle;

import cn.dqy.gotanserver.support.context.SpringContextSupport;
import cn.dqy.gotanserver.support.msghandle.impl.SimpleMsgProcess;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;

@Component
public class MsgProcessHanldeRegistrar{
    Map<Function<String,Boolean>,MsgProcessInterface> msgProcessInterfaceMap=new ConcurrentHashMap<>();
    private SimpleMsgProcess simpleMsgProcess;

    public MsgProcessInterface getProcess(String conditionParm){
        for(Function<String,Boolean> conditionFunction: msgProcessInterfaceMap.keySet()){
            if(conditionFunction.apply(conditionParm)) return msgProcessInterfaceMap.get(conditionFunction);
        }
        return simpleMsgProcess;
    }

    public <T extends MsgProcessInterface> void registrar(Function<String,Boolean> condition,Class<T> registClass){
        ApplicationContext context = SpringContextSupport.getContext();
        T bean = context.getBean(registClass);
        msgProcessInterfaceMap.put(condition,bean);
        if(SimpleMsgProcess.class.equals(registClass)) simpleMsgProcess= (SimpleMsgProcess) bean;
    }

    public Map<Function<String, Boolean>, MsgProcessInterface> getMsgProcessInterfaceMap() {
        return msgProcessInterfaceMap;
    }
}
